//
//  NSObject+wgSwizzle.m
//  Pods-WGToolDome
//
//  Created by czw on 2022/8/18.
//

#import "NSObject+wgSwizzle.h"
#import <objc/runtime.h>

@implementation NSObject (wgSwizzle)
/**
 交换方法
 @param originalSel 原来的方法
 @param swizzledSel 需要交换为的方法
 */
+ (void)wg_swizzleInstanceSelector:(SEL)originalSel
              WithSwizzledSelector:(SEL)swizzledSel {
    Method  originalMethod = class_getInstanceMethod(self, originalSel);
    Method swizzledMethod =  class_getInstanceMethod(self, swizzledSel);
    
    //如果发现方法已经存在，返回NO，也可以用来做检查用,我们这里是为了避免源方法没有实现的情况;如果方法没有存在,我们则先尝试添加被替换的方法的实现
    BOOL methodIsAdd = class_addMethod(self, originalSel,method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    if (methodIsAdd) {
        class_replaceMethod(self, swizzledSel, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    }else{
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}
@end
